package com.hkemmm.common.filter;


import cn.hutool.core.util.StrUtil;
import com.hkemmm.bean.AuthUser;
import com.hkemmm.common.service.RedisServer;
import com.hkemmm.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/auth/*")
public class MyFilter implements Filter {
    @Autowired
    private RedisServer redisServer;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println();

        String token = request.getParameter("token");
        if (StrUtil.isNotEmpty(token)) {
            AuthUser authUser = JWTUtil.getAuthUser(token);
            String resToken = (String)redisServer.get("user");

            if(StrUtil.isNotEmpty(resToken)){           //用户已登录刷新token
                //redisServer.set("user",resToken,60l*60l);
                chain.doFilter(request, response);
            }else{                                      //token失效
                System.out.println("token失效");
                request.getRequestDispatcher("/auth/login").forward(request, response);
            }
        }else{
            System.out.println("用户未登录");
            request.getRequestDispatcher("/auth/login").forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
